package com.ly.honor.util;

import cn.hutool.core.lang.UUID;
import com.ly.honor.exception.HonorException;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author 李某人
 * @Date 2023/3/13 12:26
 * @Version 1.0
 */
@Component
public class HonorUtil {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    public String uploadFile(MultipartFile file) {
        var uuid = UUID.randomUUID();
        try {
            String remoteName = minioUtil.getDatePath() + uuid + ".jpg";
            ObjectWriteResponse response = minioUtil.uploadFile(file, bucketName, remoteName);
            var url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName)
                    .object(remoteName).method(Method.GET).build());
            return url;
        } catch (Exception e) {
            throw new HonorException("上传文件失败");
        }
    }

    public String uploadVideo(MultipartFile file) {
        var uuid = UUID.randomUUID();
        try {
            String remoteName = minioUtil.getDatePath() + uuid + ".mp4";
            ObjectWriteResponse response = minioUtil.uploadFile(file, bucketName, remoteName);
            var url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName)
                    .object(remoteName).method(Method.GET).build());
            return url;
        } catch (Exception e) {
            throw new HonorException("上传视频失败");
        }
    }
}
